﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure;
using System.Net;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.IO;

namespace AzureDriverExplorer_Client
{
    /// <summary>
    /// Interaction logic for VHDUpload.xaml
    /// </summary>
    public partial class VHDCreate : Page
    {
        
        private Const cons = new Const();
        private System.Resources.ResourceManager ResManager;
        //Azure
        private static GetListVHD.AzureDriveExplorerServiceSoapClient Azure = new GetListVHD.AzureDriveExplorerServiceSoapClient();

        public VHDCreate()
        {
            InitializeComponent();
            AddConnectionLanguage();
            LoadList();
        }

        private void LoadList()
        {

            this.pictureBoxLoading.Image = Properties.Resources.reload1;
            try
            {
                if (!File.Exists(Const.FileConfig))
                { File.Create(Const.FileConfig); }
                else
                {
                    try
                    {
                        // Create an instance of StreamReader to read from a file.
                        // The using statement also closes the StreamReader.
                        using (StreamReader sr = new StreamReader(Const.FileConfig))
                        {
                            String line;
                            // Read and display lines from the file until the end of 
                            // the file is reached.
                            List<VHDDataConfig> ListConfig = new List<VHDDataConfig>();
                            while ((line = sr.ReadLine()) != null)
                            {
                                try
                                {
                                    string[] vecListConfig = line.Split(' ');
                                    VHDDataConfig GetListConfig = new VHDDataConfig(vecListConfig[0], vecListConfig[1], vecListConfig[2], vecListConfig[3]);

                                    ListConfig.Add(GetListConfig);
                                }
                                catch { }
                            }
                            ListConnection.ItemsSource = ListConfig;
                        }
                    }
                    catch (Exception ex)
                    {
                        // Let the user know what went wrong.
                        MessageBox.Show(ex.Message, string.Empty, MessageBoxButton.OK, MessageBoxImage.Error);

                    }
                }
            }
            catch (Exception ex)
            { MessageBox.Show(ex.Message + "[" + (Const.FileConfig) + "]", string.Empty, MessageBoxButton.OK, MessageBoxImage.Error); }
        }

        private void AddConnectionLanguage()
        {

            ResManager = new System.Resources.ResourceManager("AzureDriverExplorer_Client.Properties.Resources", this.GetType().Assembly);



            Title_.Text = ResManager.GetString("VHDCreate" + cons.Language).Trim();
            Create.Content=ResManager.GetString("Create" + cons.Language).Trim();
            AccountNameTitle.Text = ResManager.GetString("AccountName" + cons.Language).Trim();
            AccountKeyTitle.Text = ResManager.GetString("AccountKey" + cons.Language).Trim();
            ContainerNameTitle.Text = ResManager.GetString("ContainerName" + cons.Language).Trim();

            VHDNameTitle.Text = ResManager.GetString("VHDName" + cons.Language).Trim();
            SizeMBTitle.Text = ResManager.GetString("VHDZiseMB" + cons.Language).Trim();

            AccountName.Header = ResManager.GetString("AccountName" + cons.Language).Trim();
            ContainerName.Header = ResManager.GetString("ContainerName" + cons.Language).Trim();
            VHDName.Header = ResManager.GetString("VHDName" + cons.Language).Trim();

            Add.Content = ResManager.GetString("Add" + cons.Language).Trim();
            CancelAdd.Content = ResManager.GetString("Cancel" + cons.Language).Trim();


        }



        private void Create_Click(object sender, RoutedEventArgs e)
        {
            ReturnColor();

            if (!ValidaData())
                return;

            Enable(false);


            popupLoad.Visibility = Visibility.Visible;



            System.Threading.Thread threadImage = new System.Threading.Thread(new System.Threading.ThreadStart(delegate()
            {
                List<VHDDataConfig> ListConfig = new List<VHDDataConfig>();

                //this.pictureBoxLoading.Image = Properties.Resources.reload1;
                string AccountName = string.Empty;
                string AccountKey = string.Empty;
                string ContainerName = string.Empty;
                string VHDName = string.Empty;
                string SizeMB = string.Empty;

                Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
                {
                    AccountName = txtAccountName.Text;
                    AccountKey = txtAccountKey.Password;
                    ContainerName = txtContainerName.Text;
                    VHDName = txtVHDName.Text;
                    SizeMB = txtSizeMB.Text;

                    if (!VHDName.ToUpper().EndsWith(".VHD"))
                    { VHDName += ".vhd"; }

                }));

                try
                {


                    if (!File.Exists(Const.FileConfig))
                    { File.Create(Const.FileConfig); }
                    else
                    {


                        System.Threading.Thread.Sleep(3000);


                        try
                        {
                            // Create an instance of StreamReader to read from a file.
                            // The using statement also closes the StreamReader.
                            using (StreamReader sr = new StreamReader(Const.FileConfig))
                            {
                                String line;
                                // Read and display lines from the file until the end of 
                                // the file is reached.

                                while ((line = sr.ReadLine()) != null)
                                {
                                    try
                                    {
                                        string[] vecListConfig = line.Split(' ');
                                        VHDDataConfig GetListConfig = new VHDDataConfig(vecListConfig[0], vecListConfig[1], vecListConfig[2], vecListConfig[3]);

                                        if (GetListConfig.VHDName.Equals(VHDName))
                                        {
                                            MessageBox.Show(ResManager.GetString("Error" + cons.Language)+": "+ ResManager.GetString("VHDName" + cons.Language).Trim()+ " "+ResManager.GetString("VHDNameExist" + cons.Language), string.Empty, MessageBoxButton.OK, MessageBoxImage.Error);
                                            EnableUpdate(true);

                                            popupLoad.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
                                            {
                                                popupLoad.Visibility = Visibility.Collapsed;
                                            }));

                                            return;
                                        }
                                        ListConfig.Add(GetListConfig);
                                    }
                                    catch { }
                                }

                            }
                        }
                        catch (Exception ex)
                        {
                            // Let the user know what went wrong.
                            MessageBox.Show(ex.Message, string.Empty, MessageBoxButton.OK, MessageBoxImage.Error);

                        }
                    }

                    VHDDataConfig vhdDataConfig = new VHDDataConfig(AccountName, AccountKey, ContainerName, VHDName);
                    ListConfig.Add(vhdDataConfig);

                    string error =string.Empty;
                    try
                    {
                        error = Azure.CreateDriver(AccountName, AccountKey, ContainerName, VHDName, int.Parse(SizeMB), Const.key());
                    }
                    catch { }

                    if (error.StartsWith("0|"))
                    {
                        MessageBox.Show(ResManager.GetString("Error_AzureError" + cons.Language) + ": " + error, string.Empty, MessageBoxButton.OK, MessageBoxImage.Error);
                        EnableUpdate(true);

                        popupLoad.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
                        {
                            popupLoad.Visibility = Visibility.Collapsed;
                        }));

                        return;
                    
                    }

                    //Save in config
                    WriteFile(ListConfig);

                    //refresh list
                    ListConnection.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
                    {
                        ListConnection.ItemsSource = ListConfig;
                    }));
                }
                catch (Exception ex)
                { MessageBox.Show(ex.Message + "[" + (Const.FileConfig) + "]", string.Empty, MessageBoxButton.OK, MessageBoxImage.Error); }
                finally {
                    EnableUpdate(true);
                }



                clearAfterUpdate();
                popupLoad.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
                {
                    popupLoad.Visibility = Visibility.Collapsed;
                }));
            }));
            threadImage.Start();

            
            ReturnColor();


        }
        /// <summary>
        /// Add new line to config 
        /// </summary>
        protected void WriteFile(List<VHDDataConfig> ListConfig)
        {

            using (StreamWriter sw = new StreamWriter(Const.FileConfig))
            {
                sw.Write("");
                foreach (VHDDataConfig ValidatevhdDataConfig in ListConfig)
                {
                    sw.WriteLine(ValidatevhdDataConfig.AccountName + " " + ValidatevhdDataConfig.AccountKey + " " + ValidatevhdDataConfig.ContainerName + " " + ValidatevhdDataConfig.VHDName);
                }
                sw.Close();
            }

        }





        /// <summary>
        /// Validate data Add
        /// </summary>
        /// <returns></returns>
        private bool ValidaData()
        {
            bool Result = true;
            this.txtAccountName.Text = this.txtAccountName.Text.Replace(" ", "");
            this.txtAccountKey.Password = this.txtAccountKey.Password.Replace(" ", "");
            this.txtContainerName.Text = this.txtContainerName.Text.Replace(" ", "");
            this.txtVHDName.Text = this.txtVHDName.Text.Replace(" ", "");
            this.txtSizeMB.Text = this.txtSizeMB.Text.Replace(" ", "");


            if (this.txtAccountName.Text.Equals(string.Empty))
            {
                Result = false;
                this.txtAccountName.BorderBrush = Brushes.Red;
            }

            if (this.txtAccountKey.Password.Equals(string.Empty))
            {
                Result = false;
                this.txtAccountKey.BorderBrush = Brushes.Red;
            }

            if (this.txtContainerName.Text.Equals(string.Empty))
            {
                Result = false;
                this.txtContainerName.BorderBrush = Brushes.Red;
            }

            if (this.txtVHDName.Text.Equals(string.Empty))
            {
                Result = false;
                this.txtVHDName.BorderBrush = Brushes.Red;
            }
            if (this.txtSizeMB.Text.Equals(string.Empty))
            {
                Result = false;
                this.txtSizeMB.BorderBrush = Brushes.Red;
            }
            else
            {
                try
                {
                    int value = int.Parse(this.txtSizeMB.Text);

                    if (value < 64)
                    {
                        Result = false;
                        this.txtSizeMB.BorderBrush = Brushes.Red;
                        this.txtSizeMB.Text += ResManager.GetString("_64toup" + cons.Language);
                    }

                }
                catch
                {

                    Result = false;
                    this.txtSizeMB.BorderBrush = Brushes.Red;
                    this.txtSizeMB.Text += ResManager.GetString("OnlyNumber" + cons.Language);
                }
            }

            return Result;

        }


        /// <summary>
        /// Clear the data
        /// </summary>
        private void clear()
        {

            this.txtAccountName.Text = "";
            this.txtAccountKey.Password = "";
            this.txtContainerName.Text = "";
            this.txtVHDName.Text = "";
            this.txtSizeMB.Text = "";

        }

        /// <summary>
        /// Clear the data After update
        /// </summary>
        private void clearAfterUpdate()
        {
            this.txtAccountName.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
             {

                 this.txtAccountName.Text = "";
             }));
            this.txtAccountKey.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
            {
                this.txtAccountKey.Password = "";
            }));
            this.txtContainerName.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
           {
               this.txtContainerName.Text = "";
           }));
            this.txtVHDName.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
           {
               this.txtVHDName.Text = "";
           }));
            this.txtSizeMB.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
            {
                this.txtSizeMB.Text = "";
            }));


        }


        /// <summary>
        /// return color
        /// </summary>
        /// <returns></returns>
        private void ReturnColor()
        {

            //Add
            this.txtAccountName.BorderBrush = Brushes.AliceBlue;
            this.txtAccountKey.BorderBrush = Brushes.AliceBlue;
            this.txtContainerName.BorderBrush = Brushes.AliceBlue;
            this.txtVHDName.BorderBrush = Brushes.AliceBlue;
            this.txtSizeMB.BorderBrush = Brushes.AliceBlue;



        }

        /// <summary>
        /// Enable
        /// </summary>
        /// <param name="enable"></param>
        private void Enable(bool enable)
        {
            this.txtAccountName.IsEnabled = enable;
            this.txtAccountKey.IsEnabled = enable;
            this.txtContainerName.IsEnabled = enable;
            this.txtVHDName.IsEnabled = enable;
            this.txtSizeMB.IsEnabled = enable;
            this.CloseWindows.IsEnabled = enable;
            this.AddDataFile.IsEnabled = enable;

        }


        /// <summary>
        /// Enable in Under Prosess
        /// </summary>
        /// <param name="enable"></param>
        private void EnableUpdate(bool enable)
        {


            this.txtAccountName.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
         {
             this.txtAccountName.IsEnabled = enable;
         }));
            this.txtAccountKey.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
         {
             this.txtAccountKey.IsEnabled = enable;
         }));
            this.txtContainerName.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
         {
             this.txtContainerName.IsEnabled = enable;
         }));
            this.txtSizeMB.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
           {
               this.txtSizeMB.IsEnabled = enable;
           }));
            this.txtVHDName.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
          {
              this.txtVHDName.IsEnabled = enable;
          }));
            this.CloseWindows.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
            {
                this.CloseWindows.IsEnabled = enable;
            }));
            this.AddDataFile.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
            {
                this.AddDataFile.IsEnabled = enable;
            }));


        }

       

        private void Close_popupVhdUpload_Click(object sender, RoutedEventArgs e)
        {
            this.Visibility = Visibility.Hidden;
        }

        private void popupGetDataFile_Click(object sender, RoutedEventArgs e)
        {
            popupGetDataFile.Visibility = Visibility.Visible;
        }

        private void Close_popupGetDataFile_Click(object sender, RoutedEventArgs e)
        {
            popupGetDataFile.Visibility = Visibility.Hidden;
        }

        private void Add_popupGetDataFile_Click(object sender, RoutedEventArgs e)
        {
            if (ListConnection.SelectedItem == null)
            {
                MessageBox.Show(ResManager.GetString("Info_Select_Data_List" + cons.Language).Trim(), string.Empty, MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            VHDDataConfig GetDataConfig = ListConnection.SelectedItem as VHDDataConfig;
            txtAccountName.Text = GetDataConfig.AccountName;
            txtAccountKey.Password = GetDataConfig.AccountKey;
            txtContainerName.Text = GetDataConfig.ContainerName;

            popupGetDataFile.Visibility = Visibility.Hidden;
        }
             

    }
}
